import Vue from 'vue'
import VueRouter from 'vue-router'
import RouterList from "./router-config"
import {login_key, menu_tree, current_menu_info} from '@/config/storage-keys'
import Storage from '@/utils/storage-manage'
import Methods from '@/utils/Methods'
// 解决路由地址重复请求报错问题
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return routerPush.call(this, location).catch(error => error)
}

Vue.use(VueRouter)
let children = RouterList.map(item => {
    return {
        path: item.path,
        name: item.title,
        component: () => import('@/router/router-pages/' + item.fileName),
        meta: {
            auth: true,
            keepAlive: false,
            key: item.path,
        },
    }
})
// 异常处理页面
const other = [{
        path: "/404",
        name: "404",
        component: () => import('@/router/error-view/404.vue'),
        meta: {
            auth: true,
            keepAlive: true,
            key: "404",
        },
    }, {
        path: "/401",
        name: "401",
        component: () => import('@/router/error-view/401.vue'),
    }, {
        path: "*",
        redirect: '/404',
    }
]
// 基础路由
const routes = [{
    path: '/login',
    name: 'login',
    component: () => import('@/router/login-view/index')
}, 


{
    path: "/",
    component: () => import('@/router/home-layout/index'),
    meta: {
        auth: true,
    },
    children: children.concat(other)
}]
const Router = new VueRouter({
    // mode: 'history',
    base: process.env.BASE_URL,
    routes
})
// 测试路由
// const TestList = Testcase.map(item=>{
//     return {
//         path: item.path,
//         component: () => import('../../test/' + item.fileName),
//     }
// })
// if(process.env.NODE_ENV === 'development') {
//     Router.addRoutes(TestList)
// }
Router.beforeEach((to, from, next)=>{
	if(to.path === '/login') {
        Storage.clearLocalSrtorage()
        Storage.clearSessionStorage()
    } else {
        const userInfo = Storage.getLocalStorage(login_key)
        if(!userInfo) {
            next('/login')
        }
        if(to.path === '/') {
            const menuTree = Storage.getLocalStorage(menu_tree)
            const endChild = Methods.findFirstChildren(menuTree)
            if(endChild && endChild.path) {
                next(endChild.path)
                Storage.setSessionStorage(current_menu_info, endChild)
            }
        }
    }
	next();
})
export default Router